package com.runyu.cordova.plugin;

import com.runyu.cordova.plugin.crypto.ApplicationStarter;
import com.runyu.cordova.plugin.crypto.LicenseManager;
import com.runyu.cordova.plugin.zebra.barcode.ZebraBarcodeEventDispatcher;
import com.runyu.cordova.plugin.zebra.barcode.ZebraBarcodeManager;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * This class echoes a string called from JavaScript.
 */
public class RyBridge extends CordovaPlugin {

	private ZebraBarcodeEventDispatcher barcodeEventDispatcher;

	private LicenseManager licenseManager;

	private ApplicationStarter jsDecoder;

	private Map<String, JsActionSupport> actionMap = new HashMap<>();

	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		JsActionSupport jsActionSupport = this.actionMap.get(action);
		if (jsActionSupport != null) {
			return jsActionSupport.execute(action, args, callbackContext);
		}
		return false;
	}

	public void initialize(CordovaInterface cordova, CordovaWebView webView) {
		DeviceManager.getInstance().init(cordova.getActivity().getApplicationContext());
		this.barcodeEventDispatcher = new ZebraBarcodeEventDispatcher();
		this.jsDecoder = new ApplicationStarter(webView, cordova);
		this.licenseManager = new LicenseManager(cordova);
		ZebraBarcodeManager barcodeManager = ZebraBarcodeManager.getInstance();
		barcodeManager.registerEmdkCreatedListener(this.barcodeEventDispatcher);
		List<JsActionSupport> actionSupports = new ArrayList<>();
		actionSupports.add(this.barcodeEventDispatcher);
		actionSupports.add(this.licenseManager);
		actionSupports.add(this.jsDecoder);
		for (JsActionSupport actionSupport : actionSupports) {
			registerAction(actionSupport);
		}
		barcodeManager.init(cordova);
	}

	private void registerAction(JsActionSupport actionSupport) {
		List<String> supportActions = actionSupport.getSupportAction();
		Set<String> actionSet = this.actionMap.keySet();
		for (String action : supportActions) {
			if (actionSet.contains(action)) {
				System.err.println(action + " action overwrite !");
			}
			this.actionMap.put(action, actionSupport);
		}
	}

	public void onDestroy() {
		this.barcodeEventDispatcher.onDestroy();
	}

	public void onResume(boolean multitasking) {
		this.barcodeEventDispatcher.onResume();
	}
}
